package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.Timer;

/**
 *
 * @author Mark van der Wal
 */
public class MainFrame extends javax.swing.JFrame 
{
    private final String APPNAME = "IDP Simulation";
    private NetworkController mNetworkController;
    private Timer drawTimer;
    
    private final int RECK_DEAD = 25;
    
    // booleans
    boolean mGrab;
    boolean mStop;
    boolean mLandMode;
    boolean mAuto;
    
    /**
     * Creates new form MainFrame
     */
    public MainFrame() 
    {
        initComponents();
        
        // code init components
        this.setTitle(APPNAME);
        this.setLocationRelativeTo(null);
        
        // start message
        txtLogArea.append("[" + Logger.CurrentDate() + "]" + " Simulation opened\n");
        txtLogArea.append("=========================================================\n");
        Logger.SetLogger(txtLogArea);
        
        mNetworkController = new NetworkController();
        mNetworkController.SetNetworkListener(new NetListener());
        
        // get automated scrolling to bottom
        jScrollPane1.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() 
        {  
            @Override
            public void adjustmentValueChanged(AdjustmentEvent e) 
            {  
                txtLogArea.select(txtLogArea.getCaretPosition()*12 ,0);   
            }
        });
        drawTimer = new Timer(10, new UpdateListener());
        drawTimer.start();
        
        // init states
        mGrab = mStop = mLandMode = mAuto = false;
    }
    
    //Listens to calls from the drawTimer
    public class UpdateListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent ae)
        {
            //update the drawpanel
            drawPanel1.Update(10);
        }
    }
    
    
    public class NetListener implements NetworkListener
    {       
        @Override
        public void onNetEvent(NetEvent event) 
        {
            switch(event.getEventID())
            {
            case TYPE_CON:
                    {
                        Logger.AddLog(event.getMsg() );
                    }break;
            case TYPE_DISCON:
                    {
                        Logger.AddLog(event.getMsg() );
                        drawPanel1.ModX(0);
                        drawPanel1.ModY(0);
                    }break;
            case TYPE_RECEIVE:
                    {         
                        if((event.getMsgID() & 0xFF) == ProtocolOpcodes.T_TURN.Opcode() )
                        {
                            byte[] data = event.getData();
                            float value = data[1] & 0xFF;
                            
                            float unit = value / 127.0f - 1.0f;
                            
                           drawPanel1.ModX(unit * 2);
                        }
                        else if ( (event.getMsgID() & 0xFF) == ProtocolOpcodes.T_DRIVE.Opcode())
                        {
                            byte[] data = event.getData();
                            float value = data[1] & 0xFF;
                            
                            float unit = value / 127.0f - 1.0f;
                            
                            drawPanel1.ModY(unit * 2);
                        }
                        else if( (event.getMsgID() & 0xFF) == ProtocolOpcodes.T_COMMAND.Opcode())
                        {
                            byte[] data = event.getData();
                            int value = data[1] & 0x000000FF;
                            
                            switch(value)
                            {
                                case 1:
                                    mGrab = !mGrab;
                                    
                                    if(mGrab)
                                        Logger.AddLog("Grabber did its thing!");
                                    else
                                        Logger.AddLog("Grabber released!");
                                    break;
                                case 2:
                                    mStop = !mStop;
                                    
                                    if(mStop)
                                        Logger.AddLog("Vehicle power terminated!");
                                    else
                                        Logger.AddLog("Vehicle power Activated!");
                                    break;
                                case 3:
                                    mLandMode = !mLandMode;
                                    
                                    if(mLandMode)
                                        Logger.AddLog("Vehicle changed to land mode!");
                                    else
                                        Logger.AddLog("Vehicle changed to water mode!");
                                    break;
                                case 4:
                                    mAuto = !mAuto;
                                    if(mAuto)
                                        Logger.AddLog("Vehicle is moving autonomous!");
                                    else
                                        Logger.AddLog("Vehicle is moving by manual control!");
                                    break;
                            }
                        }
                        else // default
                        {
                            Logger.AddLog("Could not handle incoming message!");
                        }

                    }break;
            case TYPE_NOTIFI:
                    {
                        Logger.AddLog(event.getMsg() );
                    }break;
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        txtLogArea = new javax.swing.JTextArea();
        btnServer = new javax.swing.JButton();
        drawPanel1 = new main.DrawPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(640, 480));
        setName("mainFrame"); // NOI18N

        txtLogArea.setColumns(20);
        txtLogArea.setEditable(false);
        txtLogArea.setLineWrap(true);
        txtLogArea.setRows(5);
        txtLogArea.setAlignmentY(0.3F);
        txtLogArea.setFocusable(false);
        jScrollPane1.setViewportView(txtLogArea);

        btnServer.setText("Start Simulation");
        btnServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnServerActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout drawPanel1Layout = new javax.swing.GroupLayout(drawPanel1);
        drawPanel1.setLayout(drawPanel1Layout);
        drawPanel1Layout.setHorizontalGroup(
            drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 568, Short.MAX_VALUE)
        );
        drawPanel1Layout.setVerticalGroup(
            drawPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 593, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(drawPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnServer))
                .addContainerGap(438, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(581, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnServer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(drawPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(0, 34, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 599, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnServerActionPerformed
        if(!mNetworkController.IsServerStarted())
        {
            // let's try to start the server
            if(mNetworkController.Start())
            {
                btnServer.setText("Stop Simulation");
            }
        }
        else // this means the server has started and we want it to stop
        {            
            // let's try to to stop the server
            mNetworkController.Stop();
            btnServer.setText("Start Simulation");
                                    drawPanel1.ModX(0);
                        drawPanel1.ModY(0);
        }
    }//GEN-LAST:event_btnServerActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) 
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                    new MainFrame().setVisible(true);
                }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnServer;
    private main.DrawPanel drawPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtLogArea;
    // End of variables declaration//GEN-END:variables
}
